package org.microblog.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.microblog.dao.UserMapper;
import org.microblog.entity.User;
import org.microblog.service.UserService;
import org.microblog.util.DatabaseUtil;
import org.microblog.util.MyBatisUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    SqlSession sqlSession = MyBatisUtil.createSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    @Override
    public User findUser(String uId, String password) throws SQLException {
        Connection conn = null;
        try{
            conn = DatabaseUtil.getConnection();
            return userMapper.findUser(uId,password);
        }catch(SQLException e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @Override
    public int updateUser(User user) throws SQLException {
        Connection conn = null;
        try{
            return userMapper.updateUser(user);
        }catch(SQLException e){
            e.printStackTrace();
            throw e;
        }finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @Override
    public boolean findUser(String uId) throws SQLException {
        Connection conn = null;
        try{
            int result = userMapper.findUser1(uId);
            if(result==1){
                return true;
            }else{
                return false;
            }
        }catch(SQLException e){
            e.printStackTrace();
            throw e;
        }finally{
            MyBatisUtil.closeSqlSession(sqlSession);
        }
    }

    @Override
    public int register(User user) throws SQLException {
        Connection conn = null;
        int result;
        try {
            if(userMapper.findUser1(user.getUserId())==0){
                result = userMapper.register(user);
            }else{
                result = -1;
            }
            sqlSession.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            if (conn != null)
                try {
                    conn.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            throw e;
        } finally {
            MyBatisUtil.closeSqlSession(sqlSession);
        }
        return result;
    }
}
